﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MarginTrading.Entity;
using MarginTrading.Common;
using MarginTrading.Services;
using System.IO;
using System.Globalization;

namespace MarginTrading.Forms
{
    public partial class ImportFromCSV : Form
    {
        int i_Type; //  1: import clients
                    //  2: import settlement BO data file
                    //  3: import csv //TODO use suitable name

        public ImportFromCSV(int iType)
        {
            i_Type = iType;
            InitializeComponent();
        }

        //public ImportFromCSV()
        //{
        //    InitializeComponent();
        //}

        private void ImportFromCSV_Load(object sender, EventArgs e)
        {
            switch (i_Type)
            {
                case 1:
                    label1.Text = "CSV File:";
                    this.Text = "Import clients from file";
                    break;

                case 2:
                    label1.Text = "File:";
                    this.Text = "Import status from BO file";
                    break;

                case 3:
                    label1.Text = "CSV File:";
                    this.Text = "Import from CSV file";
                    break;

                case 4:
                    label2.Visible = false;
                    TrDate.Visible = false;
                    label1.Text = "CSV File:";
                    this.Text = "Import users from CSV file";
                    break;
            }
        }

        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            switch (i_Type)
            {
                case 1:
                    openFileDialog1.Filter = "CSV Files|*.csv";
                    openFileDialog1.Title = "Import Clients from CSV file";
                    break;

                case 2:
                    openFileDialog1.Filter = "All Files|*.*";
                    openFileDialog1.Title = "Import file";
                    break;

                case 3:
                    openFileDialog1.Filter = "CSV Files|*.csv";
                    openFileDialog1.Title = "Import CSV file";
                    break;

                case 4:
                    openFileDialog1.Filter = "CSV Files|*.csv";
                    openFileDialog1.Title = "Import users from CSV file";
                    break;
            }
            
            openFileDialog1.Multiselect = false;

            if (openFileDialog1.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            textBoxFilePath.Text = openFileDialog1.FileName;
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void buttonImport_Click(object sender, EventArgs e)
        {
            if (textBoxFilePath.Text == "")
            {
                MessageBox.Show("Select a file to import", "No file selected", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (File.Exists(textBoxFilePath.Text) == false)
            {
                MessageBox.Show("Failed to open file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            buttonImport.Enabled = false;

            switch (i_Type)
            {
                case 1:
                    ImportClients();
                    break;

                case 2:
                    ImportSettlementBO();
                    break;

                case 3:
                    ImportCSV2();
                    break;

                case 4:
                    ImportUsers();
                    break;
            }
            buttonImport.Enabled = true;

            //if (b_IsCSV == false)
            //{
            //    ImportNonCSV();
            //    buttonImport.Enabled = true;
            //    return;
            //}
        }

        private void ImportClients()
        {
            bool bFailed = false;
            try
            {
                using (StreamReader sr = new StreamReader(textBoxFilePath.Text))
                {
                    String line;
                    string sCode;
                    try
                    {
                        sCode = ConfigServices.GetConfigByName(Constants.CONFIG_NAME_COMPANY_CODE).Value;
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show("Error reading config. " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        buttonImport.Enabled = true;
                        return;
                    }
                    int count = 0;
                    while ((line = sr.ReadLine()) != null)
                    {
                        count++;
                        string[] attribs = line.Split(',');

                        //string sClientCode = sCode + "-" + attribs[0];
                        string sClientCode = attribs[0];
                        Client client = null;
                        bool bAdd = false;
                        try
                        {
                            client = ClientService.GetClientByCode(sClientCode);
                        }
                        catch (System.Exception ex)
                        {
                        }
                        if (client == null)
                        {
                            bAdd = true;
                            client = new Client();
                            client.Code = sClientCode;
                        }

                        client.Agent = attribs[1];
                        client.Title = attribs[2];
                        client.Initials = attribs[3];
                        //client.OtherNames = attribs[6];
                        client.Surname = attribs[4];

                        //client.Address_1 = attribs[8] + ", ";
                        //client.Address_2 = attribs[9] + ", ";
                        //client.Address_3 = attribs[10] + ", ";
                        //client.Address_4 = attribs[11];
                        client.Advisor = attribs[5];
                        //client.Telephone1 = attribs[4];
                        client.MarginLimit = Double.Parse(attribs[6]);
                        client.InterestRate = Double.Parse(attribs[7]);


                        client.MarginClient = 1;

                        client.RegDate = DateTime.Parse("05/06/2011");
                        client.MTRegDate = DateTime.Parse("05/06/2011");
                        client.Broker = "DSA";

                        try
                        {
                            if (bAdd)
                            {
                                ClientService.Add(client);
                            }
                            else
                            {
                                ClientService.Update(client);
                            }

                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show("Failed to add/update client. Error: " + ex.Message + " Line : " + count, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            bFailed = true;
                            buttonImport.Enabled = true;
                            break;
                        }

                        //try
                        //{
                        //    DailyTransactionsServices.AddInitialAccBal(client.Code, double.Parse(attribs[2]), false);
                        //}
                        //catch (System.Exception ex)
                        //{
                        //    MessageBox.Show("Failed to add initial account balance\nError: " + ex.Message + " Line : " + count, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        //    bFailed = true;
                        //    break;
                        //}
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            if (!bFailed)
            {
                MessageBox.Show("File imported successfully");
            }
        }

        private void ImportSettlementBO()
        {
            bool bFailed = false;

            string sCode;
            try
            {
                sCode = ConfigServices.GetConfigByName("Agent Code").Value;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error reading config. " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }


            string[] lines;

            try
            {
                lines = System.IO.File.ReadAllLines(textBoxFilePath.Text);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Cannot read file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            DateTime date;

            string line = lines[1];
            
            string[] attribs = line.Split('|');

            string AgentCode = "";
            try
            {
                AgentCode = attribs[6];

                if (AgentCode.Trim() != sCode.Trim())
                {
                    MessageBox.Show("Invalid file. Margin provider mismatch", "Error");
                    return;
                }

                date = DateTime.ParseExact(attribs[4], "yyyyMMdd", CultureInfo.InvariantCulture);
                //date = DateTime.Parse(attribs[2]);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Invalid file. Failed to read date", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (date.ToShortDateString() != TrDate.Value.ToShortDateString())
            {
                MessageBox.Show("Date mismatch.", "Error");
                return;
            }

            int iRecordCount;
            try
            {
                string[] values = lines[lines.Length - 1].Split('|');
                iRecordCount = int.Parse(values[1]);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Invalid file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            if (iRecordCount != lines.Length - 5)
            {
                MessageBox.Show("Invalid record count. Specified: " + iRecordCount + ", Actual: " + (lines.Length - 5).ToString(),
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            //hqdataloading culture

            //using (StreamReader sr = new StreamReader(textBoxFilePath.Text))
            //{

            //while ((line = sr.ReadLine()) != null)


            int iCount = 0;
            for (int iI = 2; iI < (lines.Length - 1); iI++)
            {
                line = lines[iI];
                attribs = line.Split('|');

                if (attribs[0] != "#0")
                    continue;

                SettlementDetails details = new SettlementDetails();

                char[] trimchars = { '0' };
                details.ClientCode = "DSA-" + attribs[1].TrimStart(trimchars);

                details.TotalDue = double.Parse(attribs[2]);
                details.Balance = double.Parse(attribs[3]);
                details.AgentCode = AgentCode;

                details.AddedDate = date;
                try
                {
                    SettlementDetailsServices.Add(details);
                }
                catch (System.Exception ex)
                {
                	continue;
                }

                iCount++;

                if (details.Balance == 0)
                {
                    continue;
                }

                LoanAccount accountEntry = new LoanAccount();

                accountEntry.Amount = details.Balance;
                accountEntry.ClientCode = details.ClientCode;
                accountEntry.CreatedDate = date;

                if (details.Balance >= 0)
                {
                    accountEntry.ReferenceNo = "PA-" + Program.GetNextSeqNO().ToString();
                    accountEntry.EntryType = "PA";
                    accountEntry.TrParticulars = "Payment-" + attribs[4]; //Cheque no
                    accountEntry.Remarks = "Payment-" + attribs[4]; 
                }
                else
                {
                    accountEntry.ReferenceNo = "RC-" + Program.GetNextSeqNO().ToString();
                    accountEntry.EntryType = "RC";
                    accountEntry.TrParticulars = "Receipt-" + attribs[4]; //Cheque no
                    accountEntry.Remarks = "Receipt-" + attribs[4]; 
                }

                try
                {
                    LoanAccountServices.Add(accountEntry);
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Added to settlement details but failed to add to loan account"
                        + Environment.NewLine + "Client Code: " + accountEntry.ClientCode + "" + Environment.NewLine + 
                        "Error : " + ex.Message, "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);

                    continue;
                }
            }

            MessageBox.Show(iCount + " records added");
            //}
        }

        private void ImportCSV2()
        {
            string[] lines;

            try
            {
                lines = System.IO.File.ReadAllLines(textBoxFilePath.Text);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Cannot read file " + textBoxFilePath.Text + ". Error: " + ex.Message,
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            string[] attribs;

            int iCount = 0;
            for (int iI = 1; iI < lines.Length; iI++)
            {
                string line = lines[iI];
                attribs = line.Split(',');

                if (attribs.Length < 10)
                {
                    continue;
                }

                MarginStatus oStatus = new MarginStatus();

                try
                {
                    oStatus.MarginDate = DateTime.ParseExact(attribs[0], "ddMMyyyy", CultureInfo.InvariantCulture);
                    //date = DateTime.Parse(attribs[2]);
                    oStatus.ClientCode = attribs[4];
                    oStatus.Agent = attribs[1];
                    oStatus.Advisor = attribs[2];
                    oStatus.ClientName = attribs[3];

                    oStatus.FacilityApproved = double.Parse(attribs[5]);
                    oStatus.PortfolioValue = double.Parse(attribs[6]);
                    oStatus.LoanBalance = double.Parse(attribs[7]);
                    oStatus.NetFutureBal = double.Parse(attribs[8]);
                    oStatus.PendingInterest = double.Parse(attribs[9]);
                    MarginStatusServices.Add(oStatus);
                    iCount++;
                }
                catch (System.Exception ex)
                {
                }
            }
            MessageBox.Show(iCount + " Records added");
        }

        private void ImportUsers()
        {
            string[] lines;

            try
            {
                lines = System.IO.File.ReadAllLines(textBoxFilePath.Text);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Cannot read file " + textBoxFilePath.Text + ". Error: " + ex.Message,
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }

            string[] attribs;

            int iAddedCount = 0;
            int iUpdatedCount = 0;
            int iFailedCount = 0;
            for (int iI = 0; iI < lines.Length; iI++)
            {
                try
                {
                    string line = lines[iI];
                    attribs = line.Split(',');

                    if (attribs.Length < 3)
                    {
                        iFailedCount++;
                        continue;
                    }

                    UserAccount userAccount = new UserAccount();
                    userAccount.UserName = attribs[0];
                    userAccount.Password = MD5Calculator.CalculateMD5Hash(attribs[1]);
                    userAccount.UserType = int.Parse(attribs[2]);

                    if (userAccount.UserType == 4)
                    {
                        Client c = null;
                        try
                        {
                            c = ClientService.GetClientByCode(userAccount.UserName);
                        }
                        catch (System.Exception ex)
                        {
                        }
                        if (c == null)
                        {
                            MessageBox.Show("Failed to find client " + userAccount.UserName, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            iFailedCount++;
                            continue;
                        }
                    }

                    UserAccount existingAccount = null;
                    try
                    {
                        existingAccount = UserAccountServices.GetUserAccountByUserName(userAccount.UserName);
                    }
                    catch (System.Exception ex)
                    {
                    }
                    if (existingAccount == null)
                    {
                        UserAccountServices.Add(userAccount);
                        iAddedCount++;
                    }
                    else
                    {
                        UserAccountServices.Update(userAccount);
                        iUpdatedCount++;
                    }
                }
                catch (System.Exception ex)
                {
                    iFailedCount++;
                }
            }

            MessageBox.Show(iAddedCount + " user accounts created. " + iUpdatedCount + " user accounts updated. " + iFailedCount + " failed");
        }
    }
}
